package com.ruoyi.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @program: ChainUp_Monitor_Rear
 * @description:
 * @author: Saumell
 * @create: 2024-07-31 16:07
 **/
public class SignUtil {
    /**
     * 生成sign
     **/
    public String toSign(String timestamp, String method, String requestPath,
                          String queryString, String body, String secretKey) throws Exception {
        // 签名串
        String preHash = preHash(timestamp, method, requestPath, queryString, body);
        byte[] secretKeyBytes = secretKey.getBytes("UTF-8");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKeySpec);
        return Hex.encodeHexString(mac.doFinal(preHash.getBytes("UTF-8")));
    }

    /**
     * 签名串
     **/
    public String preHash(String timestamp, String method, String requestPath, String queryString, String body) {
        StringBuilder preHash = new StringBuilder();
        preHash.append(timestamp);
        preHash.append(method.toUpperCase());
        preHash.append(requestPath);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(queryString)) {
            preHash.append("?").append(queryString);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(body)) {
            preHash.append(body);
        }
        return preHash.toString();
    }

    /**
     * queryString
     **/
    public String queryString(ServerHttpRequest request) {
        String url = request.getURI().toString();
        String queryString = "";
        if (url.contains("?")) {
            queryString = url.substring(url.lastIndexOf("?") + 1);
        }
        return queryString;
    }
}